package password.hb.com.password.ui;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;

import password.hb.com.password.R;
import password.hb.com.password.adapter.PasswordAdapter;
import password.hb.com.password.constant.DeliverConstant;
import password.hb.com.password.entity.Password;
import password.hb.com.password.factory.ThreadFactory;
import password.hb.com.password.model.LoginPasswordModel;
import password.hb.com.password.model.PasswordModel;
import password.hb.com.password.util.WriteFile;
import password.hb.com.password.widget.PassPopuMenu;

/**
 * Created by A on 2016/12/6.
 */

public class PasswordListActivity extends BaseActivity implements View.OnClickListener,PopupMenu.OnMenuItemClickListener{

    private SwipeMenuListView passwordList;
    private PasswordAdapter passwordAdapter;

    private FloatingActionsMenu btnMenu;
    private FloatingActionButton addActionBtn;
    private FloatingActionButton exportActionBtn;

    private TextView noPassword;

    private long systime;

    @Override
    protected void onResume() {
        super.onResume();
        initPasswordList();
    }

    @Override
    protected void onInitView(Bundle args0) {
        this.setContentViewWithActionBar(R.layout.passwordlist_activity);

        this.titlebar.setLeftVisible(false);
        this.titlebar.setRightVisible(true);
        this.titlebar.setRightAction(this);

        this.passwordList = (SwipeMenuListView) findViewById(R.id.password_list);
        this.addActionBtn = (FloatingActionButton) findViewById(R.id.add_btn);
        this.exportActionBtn = (FloatingActionButton) findViewById(R.id.export_btn);
        this.btnMenu = (FloatingActionsMenu) findViewById(R.id.btn_menu);

        noPassword = (TextView) findViewById(R.id.no_password_textView);
    }

    @Override
    protected void onSetEvent() {
        this.addActionBtn.setOnClickListener(this);
        this.exportActionBtn.setOnClickListener(this);
    }

    @Override
    protected void onInitData() {
        this.titlebar.setTitle("账号列表");
    }

    private void initPasswordList(){
        this.passwordAdapter = new PasswordAdapter(this, PasswordModel.getInstance().getAllPassword());
        this.passwordList.setAdapter(passwordAdapter);
        this.passwordList.setMenuCreator(blindedMenuCreator());
        this.passwordList.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener(){

            @Override
            public boolean onMenuItemClick(int position, SwipeMenu swipeMenu, int index) {
                passwordAdapter.remove(position);
                showOrHideNoPassword();
                return false;
            }
        });
        //listview点击事件
        this.passwordList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(PasswordListActivity.this,AddPasswordActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt(DeliverConstant.psswordIndex,position);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        showOrHideNoPassword();

    }

    //判断显示或者隐藏nopassword
    private void showOrHideNoPassword(){
        if(passwordAdapter.getPasswordList().size()>0){
            this.passwordList.setVisibility(View.VISIBLE);
            noPassword.setVisibility(View.INVISIBLE);
        }else{
            this.passwordList.setVisibility(View.INVISIBLE);
            noPassword.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onClick(View v) {
        if(v == addActionBtn){//添加密码
            Intent intent = new Intent(this,AddPasswordActivity.class);
            startActivity(intent);
            if(btnMenu.isExpanded()){
                btnMenu.collapse();
            }
        }else if(v == exportActionBtn){//导出到文本
             if(PasswordModel.getInstance().getAllPassword().size()>0) {
                 ThreadFactory.getNormalPool().execute(new Runnable() {
                     @Override
                     public void run() {
                         try {
                             WriteFile writeFile = new WriteFile("passwordList.txt");
                             for (Password p : PasswordModel.getInstance().getAllPassword()) {
                                 writeFile.write(p.toString());
                             }
                             writeFile.writeClose();
                             showToast("成功导出到passwordList.txt文件当中,\n目录为"+writeFile.getPath(),false);
                         }catch(Exception e){
                             showToast("导出失败",true);
                         }
                     }
                 });
             }else{
                 Toast.makeText(this,"还没有密码呢！",Toast.LENGTH_SHORT).show();
             }
            if(btnMenu.isExpanded()){
                btnMenu.collapse();
            }
        } else if(v == titlebar.getRightButton()){
            PassPopuMenu passPopuMenu = new PassPopuMenu(this,v);
            if(LoginPasswordModel.isHaveLoginPassword){
                passPopuMenu.remove(R.id.setting);
            }else{
                passPopuMenu.remove(R.id.reset);
            }
            passPopuMenu.setOnItemClickListener(this);
            passPopuMenu.show();
        }
    }

    private void showToast(final String content, final boolean isLenthShort){
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(isLenthShort) {
                    Toast.makeText(PasswordListActivity.this, content, Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(PasswordListActivity.this, content, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    //绑定设备列表的menu
    private SwipeMenuCreator blindedMenuCreator(){
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(
                        PasswordListActivity.this.getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
                        0xCE)));
                // set item width
                openItem.setWidth(dp2px(90));
                // set item title
                openItem.setTitle("删除");
                // set item title fontsize
                openItem.setTitleSize(18);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        PasswordListActivity.this.getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(90));
                // set a icon
                deleteItem.setIcon(R.mipmap.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        return creator;
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    //获取返回键事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTimeMillis = System.currentTimeMillis();
            if(currentTimeMillis-systime<2000){
                finish();
                android.os.Process.killProcess(android.os.Process.myPid());
            }else{
                systime = currentTimeMillis;
                Toast.makeText(this,"再按一次退出",Toast.LENGTH_SHORT).show();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        Intent intent = new Intent(this,LoginPasswordSetting.class);
        Bundle bundle = new Bundle();
        switch(item.getItemId()){
            case R.id.setting:
                bundle.putString(DeliverConstant.resetOrSetting,DeliverConstant.settingPassword);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.reset:
                bundle.putString(DeliverConstant.resetOrSetting,DeliverConstant.resetPassword);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
        }
        return true;
    }
}
